package com.omg.api.entry;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.omg.api.argument.Argument;
import com.omg.api.result.Result;
import com.omg.api.result.header.ErrorHeader;
import com.omg.constant.ResponseCode;
import com.omg.persistence.dao.lifepoint.entity.LPUser;
import com.omg.persistence.delegate.lifepoint.LPUserDelegate;

public abstract class Entry extends HttpServlet {

	private static final Logger LOG = Logger.getLogger(Entry.class.getName());

	private static final long serialVersionUID = 1L;

	private boolean needValidUser = true;

	public Entry() {
	}

	public Entry(boolean needValidUser) {
		this.needValidUser = needValidUser;
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	private void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/plain;charset=UTF-8");
		PrintWriter pw = response.getWriter();
		try {

			// step 1: valid user
			if (needValidUser) {
				validUser(request);
			}

			// step 2: fetch argument and valid error argument
			Argument argument = fetchArgument(request);

			// step 3: handle request and return result
			String result = getResult(argument);

			// step 4: push result to client

			pw.print(result);

		} catch (Exception e) {

			e.printStackTrace();

			String errorMsg = e.getMessage();

			if (errorMsg == null || errorMsg.isEmpty()) {
				errorMsg = "" + ResponseCode.AP_E_Info_UnkownError;
			}

			LOG.error(errorMsg, e);

			pw.print(getErrorResult(errorMsg));

		} finally {
			try {
				if (pw != null) {
					pw.close();
				}
			} catch (Exception e2) {
			}
		}
	}

	private final void validUser(HttpServletRequest request) throws Exception {
		String userid = request.getParameter("userid");
		if (userid == null || userid.isEmpty()) {
			throw new Exception("" + ResponseCode.AP_E_Info_InvalidUserid);
		}

		String sid = request.getParameter("sid");
		if (sid == null || sid.isEmpty()) {
			throw new Exception("" + ResponseCode.AP_E_Info_InvalidSid);
		}

		LPUser lpUser = LPUserDelegate.getInstance().getLPUserBySid(sid);

		if (lpUser == null) {
			throw new Exception("" + ResponseCode.AP_E_Info_InvalidSid);
		}

		if (!sid.equals(lpUser.getSid())) {
			throw new Exception("" + ResponseCode.AP_E_Info_InvalidSid);
		}
		// TODO 用userid、sid到缓存中或者DB中找到对应的用户信息，验证合法性
	}

	protected abstract Argument fetchArgument(HttpServletRequest request)
			throws Exception;

	protected abstract String getResult(Argument argument) throws Exception;

	/**
	 * get error msg
	 * 
	 * @param respCode
	 * @return
	 */
	private final String getErrorResult(String respCode) {
		// result
		Result result = new Result();

		// header
		ErrorHeader header = new ErrorHeader();
		header.setRespcode(respCode);
		result.setHeader(header);

		return new Gson().toJson(result);
	}
}
